﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using GBlog.Core.Service;

namespace GBlog.Core.Attributes
{
    public class NullableAttribute : ActionFilterAttribute
    {
        public string NullID { get; set; }

        public NullableAttribute() { }
        public NullableAttribute(string NullID)
        {
            this.NullID = NullID;
        }

        public NullableAttribute(bool HasID)
        {
            if (HasID)
            {
                this.NullID = "ID";
            }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!string.IsNullOrWhiteSpace(NullID) && filterContext.ActionParameters.ContainsKey(NullID))
            {
                var id = filterContext.ActionParameters[NullID] as int?;
                if (id == null)
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "NotFound" }, { "controller", "Error" } });
                }
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewResult viewResult = filterContext.Result as ViewResult;
            if (viewResult == null || viewResult.Model == null)
            {
                IErrorService service = DependencyResolver.Current.GetService<IErrorService>();

                string action = filterContext.ActionDescriptor.ActionName;
                object controller = filterContext.Controller.ControllerContext.RouteData.Values["controller"];
                Uri uri = filterContext.HttpContext.Request.UrlReferrer;
                string url = filterContext.HttpContext.Request.FilePath;
                service.Report(action, controller == null ? null : controller.ToString(), uri == null ? null : uri.ToString(), url);
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "NotFound" }, { "controller", "Error" } });
                return;
            }
        }
    }
}